package com.hmall.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class DemoGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 过滤的方法
     *
     * @param exchange 用于获取request和response对象
     * @param chain    过滤器链，用于放行
     */
    //@Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求信息
        ServerHttpRequest request = exchange.getRequest();
        //获取本次请求的uri（资源路径）
        String uri = request.getPath().toString();
        System.out.println("uri = " + uri);
        //获取本次请求携带的请求头
        String userAgent = request.getHeaders().getFirst("User-Agent");
        System.out.println("userAgent = " + userAgent);

        //获取相应对象
        ServerHttpResponse response = exchange.getResponse();
        //如果要拦截不放行：
        //   设置响应状态码
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //   立即结束并返回响应
        //return response.setComplete();

        //如果要放行
        return chain.filter(exchange);
    }


    /**
     * 过滤器的执行优先级
     *
     * @return 整数值，值越小，过滤器执行地越早
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
